// PLC持续监控功能测试脚本

// 模拟PLC服务
class MockPLCService {
  constructor() {
    this.variables = {
      'DB1,W0.0': 25,    // 温度
      'DB1,W2.0': 60,    // 湿度
      'DB1,W4.0': 1,     // 货架状态
      'DB1,W6.0': 1      // 系统状态
    };
    
    // 定时更新模拟变量值
    this.updateInterval = setInterval(() => {
      // 随机更新温度值
      this.variables['DB1,W0.0'] = 20 + Math.random() * 15;
      
      // 随机更新湿度值
      this.variables['DB1,W2.0'] = 50 + Math.random() * 30;
      
      // 随机切换货架状态
      if (Math.random() > 0.7) {
        this.variables['DB1,W4.0'] = this.variables['DB1,W4.0'] === 0 ? 1 : 0;
      }
    }, 2000);
  }
  
  // 模拟读取变量
  async readVariables(variables) {
    const result = {};
    variables.forEach(variable => {
      result[variable] = this.variables[variable];
    });
    return result;
  }
  
  // 模拟写入变量
  async writeVariable(variable, value) {
    this.variables[variable] = value;
    return { success: true, variable, value };
  }
  
  // 停止模拟更新
  stop() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
    }
  }
}

// 模拟PLC服务实例
const mockPLC = new MockPLCService();

// PLC监控服务
class PLCMonitoringService {
  constructor() {
    this.monitoringVariables = new Map();
    this.monitoringInterval = null;
    this.monitoringIntervalTime = 1000;
  }
  
  // 启动监控
  startMonitoring(variables, callback, intervalTime = 1000) {
    this.stopMonitoring();
    this.monitoringIntervalTime = intervalTime;
    
    variables.forEach(variable => {
      this.monitoringVariables.set(variable, { 
        lastValue: null, 
        callback: callback,
        errorCount: 0
      });
    });
    
    this._runMonitoringLoop();
    console.log(`✅ 启动PLC变量监控，监控 ${variables.length} 个变量，间隔 ${intervalTime}ms`);
  }
  
  // 停止监控
  stopMonitoring() {
    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval);
      this.monitoringInterval = null;
    }
    
    this.monitoringVariables.clear();
    console.log('🛑 停止PLC变量监控');
  }
  
  // 添加变量到监控列表
  addMonitoringVariable(variable, callback) {
    this.monitoringVariables.set(variable, { 
      lastValue: null, 
      callback: callback,
      errorCount: 0
    });
    
    if (!this.monitoringInterval) {
      this._runMonitoringLoop();
    }
    
    console.log(`➕ 添加变量到监控列表: ${variable}`);
  }
  
  // 从监控列表中移除变量
  removeMonitoringVariable(variable) {
    this.monitoringVariables.delete(variable);
    console.log(`➖ 从监控列表中移除变量: ${variable}`);
  }
  
  // 运行监控循环
  async _runMonitoringLoop() {
    this.monitoringInterval = setInterval(async () => {
      if (this.monitoringVariables.size === 0) return;
      
      try {
        const variables = Array.from(this.monitoringVariables.keys());
        const values = await mockPLC.readVariables(variables);
        
        for (const variable of variables) {
          const variableInfo = this.monitoringVariables.get(variable);
          const newValue = values[variable];
          
          if (variableInfo.lastValue !== newValue) {
            if (variableInfo.callback) {
              try {
                variableInfo.callback(variable, newValue, variableInfo.lastValue);
              } catch (err) {
                console.error(`❌ 监控变量回调执行失败 ${variable}:`, err);
              }
            }
            
            variableInfo.lastValue = newValue;
            variableInfo.errorCount = 0;
          }
        }
      } catch (err) {
        console.error('❌ PLC监控循环执行失败:', err);
        
        for (const [variable, info] of this.monitoringVariables.entries()) {
          info.errorCount++;
          if (info.errorCount > 5) {
            console.warn(`⚠️ 变量 ${variable} 连续错误超过阈值，从监控中移除`);
            this.monitoringVariables.delete(variable);
          }
        }
      }
    }, this.monitoringIntervalTime);
  }
}

// 测试PLC监控功能
async function testPLCMonitoring() {
  console.log('🚀 开始PLC持续监控功能测试...');
  
  const plcMonitoring = new PLCMonitoringService();
  
  // 定义要监控的变量
  const monitoredVariables = [
    'DB1,W0.0',  // 温度
    'DB1,W2.0',  // 湿度
    'DB1,W4.0',  // 货架状态
    'DB1,W6.0'   // 系统状态
  ];
  
  // 启动监控
  plcMonitoring.startMonitoring(monitoredVariables, (variable, newValue, oldValue) => {
    console.log(`📊 ${variable} 变化: ${oldValue} → ${newValue}`);
    
    // 根据变量类型进行特殊处理
    switch (variable) {
      case 'DB1,W0.0': // 温度监控
        if (newValue > 30) {
          console.warn(`⚠️ 温度过高警告: ${newValue.toFixed(1)}°C`);
        }
        break;
        
      case 'DB1,W2.0': // 湿度监控
        if (newValue > 80) {
          console.warn(`⚠️ 湿度过高警告: ${newValue.toFixed(1)}%`);
        }
        break;
    }
  }, 500);
  
  // 3秒后动态添加一个变量
  setTimeout(() => {
    console.log('\n➕ 3秒后动态添加变量 DB1,W8.0');
    plcMonitoring.addMonitoringVariable('DB1,W8.0', (variable, newValue, oldValue) => {
      console.log(`📈 动态监控变量 ${variable}: ${oldValue} → ${newValue}`);
    });
  }, 3000);
  
  // 6秒后动态移除一个变量
  setTimeout(() => {
    console.log('\n➖ 6秒后动态移除变量 DB1,W8.0');
    plcMonitoring.removeMonitoringVariable('DB1,W8.0');
  }, 6000);
  
  // 10秒后停止监控
  setTimeout(() => {
    console.log('\n🛑 10秒后停止监控');
    plcMonitoring.stopMonitoring();
    mockPLC.stop();
    console.log('✅ PLC持续监控功能测试完成');
  }, 10000);
}

// 运行测试
testPLCMonitoring().catch(console.error);

module.exports = { MockPLCService, PLCMonitoringService };